package com.ruoyi.nsh.controller;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.nsh.domain.BusinessDepositRegister;
import com.ruoyi.nsh.service.IBusinessDepositRegisterService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.utils.file.FileUploadUtils;
import org.springframework.beans.factory.annotation.Value;
import com.ruoyi.common.config.RuoYiConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import org.apache.commons.io.FileUtils;
//import com.ruoyi.common.utils.DateUtils;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 存款预约登记Controller
 * 
 * @author yys
 * @date 2025-01-13
 */
@RestController
@RequestMapping("/proprice/deposit")
public class BusinessDepositRegisterController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(BusinessDepositRegisterController.class);

    @Autowired
    private IBusinessDepositRegisterService businessDepositRegisterService;

    @Value("${file.path}")
    private String uploadPath;
    
    @Value("${file.allowed-types}")
    private String allowedTypes;
    
    @Value("${file.max-size}")
    private long maxFileSize;

    /**
     * 查询存款预约登记列表
     */
    @PreAuthorize("@ss.hasPermi('proprice:deposit:list')")
    @GetMapping("/list")
    public TableDataInfo list(BusinessDepositRegister businessDepositRegister)
    {
        startPage();
        List<BusinessDepositRegister> list = businessDepositRegisterService.selectBusinessDepositRegisterList(businessDepositRegister);
        return getDataTable(list);
    }

    /**
     * 导出存款预约登记列表
     */
    @PreAuthorize("@ss.hasPermi('proprice:deposit:export')")
    @Log(title = "存款预约登记", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BusinessDepositRegister businessDepositRegister)
    {
        List<BusinessDepositRegister> list = businessDepositRegisterService.selectBusinessDepositRegisterList(businessDepositRegister);
        ExcelUtil<BusinessDepositRegister> util = new ExcelUtil<BusinessDepositRegister>(BusinessDepositRegister.class);
        util.exportExcel(response, list, "存款预约登记数据");
    }

    /**
     * 获取存款预约登记详细信息
     */
    @PreAuthorize("@ss.hasPermi('proprice:deposit:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(businessDepositRegisterService.selectBusinessDepositRegisterById(id));
    }

    /**
     * 新增存款预约登记
     */
    @PreAuthorize("@ss.hasPermi('proprice:deposit:add')")
    @Log(title = "存款预约登记", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BusinessDepositRegister businessDepositRegister)
    {
        return toAjax(businessDepositRegisterService.insertBusinessDepositRegister(businessDepositRegister));
    }

    /**
     * 修改存款预约登记
     */
    @PreAuthorize("@ss.hasPermi('proprice:deposit:edit')")
    @Log(title = "存款预约登记", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BusinessDepositRegister businessDepositRegister)
    {
        return toAjax(businessDepositRegisterService.updateBusinessDepositRegister(businessDepositRegister));
    }

    /**
     * 删除存款预约登记
     */
    @PreAuthorize("@ss.hasPermi('proprice:deposit:remove')")
    @Log(title = "存款预约登记", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(businessDepositRegisterService.deleteBusinessDepositRegisterByIds(ids));
    }

    /**
     * 上传附件
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 校验文件类型
            String extension = FilenameUtils.getExtension(file.getOriginalFilename());
            if (!allowedTypes.contains("." + extension.toLowerCase())) {
                return AjaxResult.error("不支持的文件类型");
            }
            
            // 校验文件大小
            if (file.getSize() > maxFileSize) {
                return AjaxResult.error("文件大小不能超过10MB");
            }
            
            // 使用增加了MD5检查的上传方法
            String url = FileUploadUtils.uploadFile(RuoYiConfig.getProfile(), file);
            
            Map<String, Object> data = new HashMap<>();
            data.put("url", url);
            data.put("fileName", file.getOriginalFilename());
            
            return AjaxResult.success(data);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 下载附件
     */
    @PreAuthorize("@ss.hasPermi('proprice:deposit:query')")
    @GetMapping("/download")
    public void downloadFile(@RequestParam("fileName") String fileName, HttpServletResponse response) throws IOException {
        try {
            // 获取文件路径
            String filePath = RuoYiConfig.getProfile();
            
            // 从url中提取文件名
            String realFileName = fileName;
            if (realFileName.startsWith("/profile/")) {
                realFileName = realFileName.substring("/profile/".length());
            } else if (realFileName.startsWith("/profile")) {
                realFileName = realFileName.substring("/profile".length());
            }
            
            // 构建文件完整路径
            File file = new File(filePath + File.separator + realFileName);
            
            if (!file.exists()) {
                throw new RuntimeException("文件不存在: " + realFileName);
            }

            // 获取原始文件名
            String originalFileName = realFileName;
            if (originalFileName.contains("/")) {
                originalFileName = originalFileName.substring(originalFileName.lastIndexOf("/") + 1);
            }
            // 如果文件名包含时间戳前缀，则提取原始文件名部分
            if (originalFileName.contains("_")) {
                originalFileName = originalFileName.substring(originalFileName.indexOf("_") + 1);
            }

            // 设置响应头
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", 
                "attachment;filename=" + URLEncoder.encode(originalFileName, "UTF-8"));

            // 写入响应流
            FileUtils.copyFile(file, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败: {}", fileName, e);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, Object> error = new HashMap<>();
            error.put("code", 500);
            error.put("msg", e.getMessage());
            response.getWriter().write(new ObjectMapper().writeValueAsString(error));
        }
    }
}
